//
// Created by twlin on 2024/8/6.
//
#include <csocket.h>
#include <sys/socket.h>
//#include <netinet/in.h>
//#include <cstring>
#include <arpa/inet.h>
#include <errno.h>
#include <iostream>


int CSocket::create(int family, int type, int protocol)
{
    return ::socket(family, type, protocol);
}

int CSocket::error()
{
    return errno;
}

bool CSocket::bind(socket_t so, struct sockaddr *addr, socklen_t len)
{
    if (so == INVALID_SOCKET)
    {
        perror("Invalid socket.");
        return false;
    }

    if (::bind(so, addr, len) == -1)
    {
        perror("Bind error");
        return false;
    }

    return true;
}

bool CSocket::setsockopt(socket_t so, int level, int optname, const void *optval, socklen_t optlen)
{
    if(::setsockopt(so, level, optname, optval,optlen) < 0)
    {
        perror("Create socket fail");
        return false;
    }
    return true;
}

bool CSocket::listen(socket_t so, int listen)
{
    if (::listen(so, listen) == -1)
    {
        perror("Listen error");
        return false;
    }
    return true;
}

int CSocket::accept(socket_t so, struct sockaddr *addr, socklen_t *addrlen)
{
    if(so == INVALID_SOCKET)
    {
        perror("Invalid socket.");
        return INVALID_SOCKET;
    }

    int sockfd = ::accept(so, addr, addrlen);
    if (sockfd == INVALID_SOCKET)
    {
        perror("Accept failed:");
        return INVALID_SOCKET;
    }
    return sockfd;
}

bool CSocket::connect(socket_t so, struct sockaddr *addr, socklen_t addrlen)
{
    if(::connect(so, addr, addrlen) < 0)
    {
        perror("connect error");
        return false;
    }
    return true;
}

ssize_t CSocket::send(socket_t fd, const void *buf, size_t n, int flags)
{
    if(fd == INVALID_SOCKET)
    {
        perror("Invalid socket.");
        return INVALID_SOCKET;
    }
    return ::send(fd, buf, n, flags);
}

ssize_t CSocket::recv(socket_t fd, void *buf, size_t n, int flags)
{
    if(fd == INVALID_SOCKET)
    {
        perror("Invalid socket.");
        return INVALID_SOCKET;
    }
    return ::recv(fd, buf, n, flags);
}

int CSocket::close(socket_t fd)
{
    if(fd == INVALID_SOCKET)
    {
        perror("Invalid socket.");
        return INVALID_SOCKET;
    }
    return ::close(fd);
}


